package dangan.danganDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import dangan.bean.StudentBean;
import util.JDBCUtils;

public class StudentDao {

	Connection con=null;
	PreparedStatement ps=null;
	
	public String insert(StudentBean stu) throws SQLException {
		String sql="insert into d_student(id,name,zhuanye,sex) values(?,?,?,?)";
		
		try {
			con=JDBCUtils.getConnection();
			//预备集没获取
			ps=con.prepareStatement(sql);
			ps.setInt(1, stu.getId());
			ps.setString(2, stu.getName());
			ps.setString(3, stu.getZhuanye());
			ps.setInt(4, stu.getSex());
			return ps.executeUpdate()+"";
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			JDBCUtils.close( null, ps, con);
		}
		return "——————insert";
		
	}
	public List<StudentBean> selectAll(){
		
		String sql="select * from d_student";
		ResultSet rs=null;
		List<StudentBean> list=new ArrayList<>();
		try {
			con=JDBCUtils.getConnection();
			ps=con.prepareStatement(sql);
			rs=ps.executeQuery();
			while(rs.next()) {
				StudentBean stu=new StudentBean();
				stu.setId(rs.getInt("id"));
				stu.setName(rs.getString("name"));
				stu.setZhuanye(rs.getString("zhuanye"));
				stu.setSex(rs.getInt("sex"));
				list.add(stu);
			}
			return list;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtils.close(rs, ps, con);
		}
		return list;
	}
	
	public List<StudentBean> selectByName(StudentBean stu){
		String sql="select*from d_student where name=?";
		ResultSet rs=null;
		List<StudentBean> list =new ArrayList<>();
		try {
			con=JDBCUtils.getConnection();
			ps=con.prepareStatement(sql);
			ps.setString(1, stu.getName());
			ps.executeQuery();
			rs=ps.executeQuery();
			while(rs.next()) {
				StudentBean stu1=new StudentBean();
				stu1.setId(rs.getInt("id"));
				stu1.setName(rs.getString("name"));
				stu1.setZhuanye(rs.getString("zhuanye"));
				stu1.setSex(rs.getInt("sex"));
				list.add(stu1);
			}
			return list;
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			JDBCUtils.close(rs, ps, con);
		}
		return list;
	}
	
	public List<StudentBean> selectByZhuan(StudentBean stu){
		String sql="select*from d_student where zhuanye=?";
		ResultSet rs=null;
		List<StudentBean> list=new ArrayList<>();
		try {
			con=JDBCUtils.getConnection();
			ps=con.prepareStatement(sql);
			ps.setString(1,stu.getZhuanye());
			rs=ps.executeQuery();
			while(rs.next()) {
				StudentBean stu1=new StudentBean();
				stu1.setId(rs.getInt("id"));
				stu1.setName(rs.getString("name"));
				stu1.setZhuanye(rs.getString("zhuanye"));
				stu1.setSex(rs.getInt("sex"));
				list.add(stu1);
			}
			return list;
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			JDBCUtils.close(rs, ps, con);
		}
		return list;
		
	}
}
